package com.extension.company.common.mvp;

import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import com.extension.company.admin.R;
import com.jaeger.library.StatusBarUtil;

import butterknife.ButterKnife;

public abstract class BaseActivity<V extends IView, P extends BasePresenter> extends AppCompatActivity {

	protected P presenter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置键盘默认隐藏
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		setContentView(getMainLayout());

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			//sdk大于或等于11
			//启动硬件加速
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
					WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
		}
		//创建Presenter
		presenter = createPresenter();
		if (presenter != null) {
			//将View层注册到Presenter中
			presenter.registerView(createView());
			//将Mode层注册到presenter
			presenter.registerModel();
		}
		ButterKnife.bind(this);
		initData();
		initListener();
	}

	protected abstract void initData();

	protected abstract void initListener();

	/**
	 * 获得主界面layout资源
	 *
	 * @return
	 */
	public abstract int getMainLayout();

	public abstract V createView();

	public abstract P createPresenter();

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		if (newConfig.fontScale != 1) {
			//非默认值
			getResources();
		}
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public Resources getResources() {
		Resources res = super.getResources();
		if (res.getConfiguration().fontScale != 1) {//非默认值
			Configuration newConfig = new Configuration();
			newConfig.setToDefaults();//设置默认
			res.updateConfiguration(newConfig, res.getDisplayMetrics());
		}
		return res;
	}

	/**
	 * 取消方法
	 */
	public void onBtnCancel() {
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			onBtnCancel();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (presenter != null) {
			//Activity销毁时的调用，让具体实现BasePresenter中onViewDestroy()方法做出决定
			presenter.destroy();
		}
	}
}
